package cn.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;

import cn.kpi.entity.sys.Configure;
import cn.kpi.entity.sys.OrgEntity;
import cn.kpi.service.sys.IConfigureService;
import cn.kpi.service.sys.IOrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import cn.common.ConfigOption;
import cn.common.ExceResult;
import cn.common.ExcelHandler;
import cn.common.GridCommon;
import cn.common.LayTable;
import cn.filter.LoginCheck;
import cn.kpi.entity.attendance.AttDetailEntity;
import cn.kpi.entity.attendance.AttSummaryEntity;
import cn.kpi.entity.attendance.AttTbBatchEntity;
import cn.kpi.entity.sys.UserEntity;
import cn.kpi.service.attendance.IAttBmHzService;
import cn.kpi.service.attendance.IAttTbService;
import cn.kpi.service.common.IOrgSummaryService;
import cn.kpi.service.sys.IUserService;
import sun.misc.BASE64Decoder;

@Controller
@RequestMapping("attbmhz")
public class AttBmHzController extends BaseController {

    @Autowired
    private IOrgService iOrgService;
    @Autowired
    private IConfigureService configureService;
    @Autowired
    private IAttTbService iAttTbService;

    @Autowired
    private IAttBmHzService iAttBmHzService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IOrgSummaryService iOrgSummaryService;

    @RequestMapping(value = "/att_bm_hz_list")
    public String AttBmHzList(Model model) {
        try {

            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;
            if (month == 1) {
                year = year - 1;
                month = 12;
            } else {
                month--;
            }

            model.addAttribute("year", year);
            model.addAttribute("month", month);
        } catch (Exception ex) {

        }
        return "attendance/att_bm_hz_list";
    }

    @RequestMapping(value = "/lookPdf")
    public String lookPDf(Model model) {
        try {


        } catch (Exception ex) {

        }
        return "attendance/att_bm_look";
    }


    @RequestMapping(value = "/att_bm_sh_list")
    public String AttShList(Model model) {
        try {
            Calendar cale = Calendar.getInstance();
            int year = cale.get(Calendar.YEAR);
            model.addAttribute("year", year);
            UserEntity user = this.GetLoginUser();
            String userName = user.getRealname();
            model.addAttribute("deptName", user.getOrgname());
            model.addAttribute("orgname", userName);
        } catch (Exception ex) {

        }
        return "attendance/att_bm_sh_list";
    }


    @RequestMapping(value = "/att_bm_hz_edit")
    public String AttBmHzEdit(Model model, Long attsummaryid, Long orgsummaryid) {
        try {
            List<AttDetailEntity> list = iAttBmHzService.GetAttDetailBySummayId(attsummaryid, orgsummaryid);
            model.addAttribute("list", list);

            UserEntity userentity = iUserService.GetUserById(list.get(0).getUserid());
            model.addAttribute("userentity", userentity);

            String detailids = "";
            for (int i = 0; i < list.size(); i++) {
                detailids += list.get(i).getAttdetailid() + ",";
            }
            model.addAttribute("detailids", detailids);
            model.addAttribute("attsummaryid", attsummaryid);

        } catch (Exception ex) {

        }
        return "attendance/att_bm_hz_edit";
    }

    @RequestMapping(value = "/att_bm_hz_edit_nodetail")
    public String AttBmHzEditNoDetail(Model model, Long userid, Long attsummaryid, Long orgsummaryid) {
        try {
            UserEntity userentity = iUserService.GetUserById(userid);
            model.addAttribute("userentity", userentity);


            AttSummaryEntity sumentity = iAttTbService.GetAttTbAttsummaryById(attsummaryid);

            model.addAttribute("attsummaryid", attsummaryid);

            model.addAttribute("sumentity", sumentity);

        } catch (Exception ex) {

        }
        return "attendance/att_bm_hz_edit_nodetail";
    }


    @RequestMapping(value = "/att_bm_hz_show")
    public String AttBmHzShow(Model model, Long attsummaryid, Long orgsummaryid) {
        try {
            List<AttDetailEntity> list = iAttBmHzService.GetAttDetailBySummayId(attsummaryid, orgsummaryid);
            model.addAttribute("list", list);

            UserEntity userentity = iUserService.GetUserById(list.get(0).getUserid());
            model.addAttribute("userentity", userentity);

            String detailids = "";
            for (int i = 0; i < list.size(); i++) {
                detailids += list.get(i).getAttdetailid() + ",";
            }
            model.addAttribute("detailids", detailids);
            model.addAttribute("attsummaryid", attsummaryid);

        } catch (Exception ex) {

        }
        return "attendance/att_bm_hz_show";
    }


    @RequestMapping(value = "/att_bm_cx_list")
    public String AttcxList(Model model) {
        try {
//            UserEntity user = this.GetLoginUser();
//            String userName = user.getRealname();
//            model.addAttribute("deptName", user.getOrgname());
//            model.addAttribute("orgname", userName);
        } catch (Exception ex) {

        }
        return "attendance/att_bm_cx_list";
    }


    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/getNotUser")
    public int GetNotInUser(HttpServletRequest request) {

        try {

            List<AttSummaryEntity> lst = null;
            LayTable<AttSummaryEntity> layTable = new LayTable<AttSummaryEntity>();


            String year = request.getParameter("year");
            String mouth = request.getParameter("mouth");

            String orgid = request.getParameter("orgid");
            String orgsummaryid = request.getParameter("orgsummaryid");

            String realname = request.getParameter("realname");


            String where = "";


            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (mouth != null && mouth.length() > 0) {
                where += " AND mouth=" + mouth;
            }

            if (orgid != null && orgid.length() > 0 && !orgid.equals("0")) {
                where += " AND szdw IN (" + orgid + ")";
            } else {
                where += " AND szdw IN (" + this.GetOrgListByRole() + ")";
            }

            if (orgsummaryid != null && orgsummaryid.length() > 0 && !orgsummaryid.equals("0")) {
                where += " AND orgsummaryid=" + orgsummaryid;
            }

            if (realname != null && realname.length() > 0) {
                where += " AND userid IN (SELECT userid FROM t_sys_user WHERE cardno LIKE '%" + realname + "%'  or realname LIKE '%" + realname + "%')";
            }


            return iAttTbService.GetAttTbListNotUser(where, orgid).size();


        } catch (Exception ex) {
            return 0;

        }


    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_list")
    public LayTable<AttSummaryEntity> GetList(HttpServletRequest request) {

        List<AttSummaryEntity> lst = null;
        LayTable<AttSummaryEntity> layTable = new LayTable<AttSummaryEntity>();
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));

            String year = request.getParameter("year");
            String mouth = request.getParameter("mouth");

            String orgid = request.getParameter("orgid");
            String orgsummaryid = request.getParameter("orgsummaryid");

            String realname = request.getParameter("realname");
            String status = request.getParameter("status");

            String where = "";


            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (mouth != null && mouth.length() > 0) {
                where += " AND mouth=" + mouth;
            }

            if (orgid != null && orgid.length() > 0 && !orgid.equals("0")) {
                where += " AND szdw IN (" + orgid + ")";
            } else {
                where += " AND szdw IN (" + this.GetOrgListByRole() + ")";
            }

            if (orgsummaryid != null && orgsummaryid.length() > 0 && !orgsummaryid.equals("0")) {
                where += " AND orgsummaryid=" + orgsummaryid;
            }

            if (realname != null && realname.length() > 0) {
                where += " AND userid IN (SELECT userid FROM t_sys_user WHERE cardno LIKE '%" + realname + "%'  or realname LIKE '%" + realname + "%')";
            }

            int beginrow = (page - 1) * limit;
            int endrow = limit;

            String wherelimit = where + " LIMIT " + beginrow + "," + endrow;


            if (status != null && status.equals("2")) {
                lst = iAttTbService.GetAttTbListByWhere(wherelimit);

            } else {
                lst = iAttTbService.GetAttTbListByUser(wherelimit, orgid);
            }

            for (int i = 0; i < lst.size(); i++) {
                int rownum = (page - 1) * limit + (i + 1);
                lst.get(i).setRowNum(rownum);
                //AttSummaryEntity summaryentity=lst.get(i);


            }

            int iCount = iAttTbService.GetAttTbListCountByWhere(where);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_sh_list")
    public LayTable<AttSummaryEntity> GetShList(HttpServletRequest request) {

        List<AttSummaryEntity> lst = null;
        LayTable<AttSummaryEntity> layTable = new LayTable<AttSummaryEntity>();
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));

            String year = request.getParameter("year");
            String mouth = request.getParameter("mouth");

            String orgid = request.getParameter("orgid");
            String orgsummaryid = request.getParameter("orgsummaryid");

            String realname = request.getParameter("realname");
            String status = request.getParameter("status");

            String where = "";


            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (mouth != null && mouth.length() > 0) {
                where += " AND mouth=" + mouth;
            }

            if (orgid != null && orgid.length() > 0 && !orgid.equals("0")) {
                where += " AND szdw IN (" + orgid + ")";
            } else {
                where += " AND szdw IN (" + this.GetOrgListByRole() + ")";
            }

            if (orgsummaryid != null && orgsummaryid.length() > 0 && !orgsummaryid.equals("0")) {
                where += " AND orgsummaryid=" + orgsummaryid;
            }

            if (realname != null && realname.length() > 0) {
                where += " AND userid IN (SELECT userid FROM t_sys_user WHERE cardno LIKE '%" + realname + "%'  or realname LIKE '%" + realname + "%')";
            }

            int beginrow = (page - 1) * limit;
            int endrow = limit;

            String wherelimit = where + " LIMIT " + beginrow + "," + endrow;


            lst = iAttTbService.GetAttTbListByWhere(wherelimit);

            for (int i = 0; i < lst.size(); i++) {
                int rownum = (page - 1) * limit + (i + 1);
                lst.get(i).setRowNum(rownum);
            }

            int iCount = iAttTbService.GetAttTbListCountByWhere(where);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }


    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_cx_list")
    public LayTable<AttSummaryEntity> GetcxList(HttpServletRequest request) {

        List<AttSummaryEntity> lst = null;
        LayTable<AttSummaryEntity> layTable = new LayTable<AttSummaryEntity>();
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));

            String start = request.getParameter("start");
            String end = request.getParameter("endt");

            String orgid = request.getParameter("orgid");

            String realname = request.getParameter("realname");
            String status = request.getParameter("atttype");

            String where = " ";//取出非零
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);

            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM");
            if (start != null && start.length() > 0) {
                Date date = sDateFormat.parse(start);
                Calendar cale = Calendar.getInstance();
                cale.setTime(date);
                int yeare = cale.get(Calendar.YEAR);
                int monthe = cale.get(Calendar.MONTH) + 1;
                where += " AND year >= " + yeare + " AND mouth >= " + monthe;
            } else {

                Date date = new Date();
                where += " AND year >= " + year + " AND mouth >= " + month;
            }

            if (end != null && end.length() > 0) {
                Date date = sDateFormat.parse(end);
                Calendar cale = Calendar.getInstance();
                cale.setTime(date);
                int yeare = cale.get(Calendar.YEAR);
                int monthe = cale.get(Calendar.MONTH) + 1;
                where += " AND year <= " + yeare + " AND mouth <= " + monthe;
            } else {
                Date date = new Date();
                where += " AND year <= " + year + " AND mouth <= " + month;
            }

            if (orgid != null && orgid.length() > 0 && !orgid.equals("0")) {
                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(orgid));
                where += " AND szdw IN (SELECT orgid FROM t_sys_org WHERE lft>= " + orgentity.getLft() + " AND lft<=" + orgentity.getRgt() + ")";
            } else {
                where += " AND szdw IN (" + this.GetOrgListByRole() + ")";
            }

            if (realname != null && realname.length() > 0) {
                where += " AND userid IN (SELECT userid FROM t_sys_user WHERE cardno LIKE '%" + realname + "%'  or realname LIKE '%" + realname + "%')";
            }

            if (status != null && status.length() > 0 && !status.contains("00")) {
                if (status.contains(",")) {
                    String[] str = status.split(",");
                    for (int i = 0; i < str.length; i++) {
                        if (i == 0) {
                            where += " AND (" + getStatue(Integer.valueOf(str[i]));
                        } else {
                            where += " OR " + getStatue(Integer.valueOf(str[i]));
                        }

                    }
                    where += ") ";
                } else {
                    where += " AND " + getStatue(Integer.valueOf(status));
                }
            } else {

                where += " AND wcqtsxj > 0 ";
            }

            int beginrow = (page - 1) * limit;
            int endrow = limit;

            String wherelimit = where + " LIMIT " + beginrow + "," + endrow;


            lst = iAttTbService.GetAttTbListByWhere(wherelimit);

            for (int i = 0; i < lst.size(); i++) {
                int rownum = (page - 1) * limit + (i + 1);
                lst.get(i).setRowNum(rownum);
            }

            int iCount = iAttTbService.GetAttTbListCountByWhere(where);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }

    private String getStatue(Integer status) {
        String where = "";
        switch (status) {
            case 1:
                where = "  xjts > 0 ";
                break;
            case 2:
                where = "  tqjts > 0 ";
                break;
            case 3:
                where = "  hjts >0 ";
                break;
            case 4:
                where = "  syjts >0 ";
                break;
            case 5:
                where = "  sangjts >0 ";
                break;
            case 6:
                where = "  gsts >0 ";
                break;
            case 7:
                where = "  bjts >0 ";
                break;
            case 8:
                where = "  sjts >0 ";
                break;
            case 9:
                where = "  qtts >0 ";
                break;
            case 10:
                where = "  cdcc >0 ";
                break;
            case 11:
                where = "  ztcc >0 ";
                break;
            case 12:
                where = "  kgcs >0 ";
                break;
        }
        return where;
    }


    @RequestMapping(value = "/add_attbmhz")
    public String AddAttBmHz(HttpServletRequest request, HttpServletResponse response) {
        try {
            String detailids = request.getParameter("detailids");
            String strattsummaryid = request.getParameter("attsummaryid");


            if (detailids == null || detailids.length() <= 0) {
                return renderStringScript(response, "<script>window.parent.CloseDialog(0,'参数有误')</script>");
            }

            String[] detailArr = detailids.split(",");

            System.out.println(detailArr.length);

            List<AttDetailEntity> lst = new ArrayList<AttDetailEntity>();
            for (int i = 0; i < detailArr.length; i++) {
                Long detailid = Long.parseLong(detailArr[i]);
                AttDetailEntity item = new AttDetailEntity();
                item.setBj(Float.parseFloat(request.getParameter("bj_" + detailid)));//病假
                item.setCd(Integer.parseInt(request.getParameter("cd_" + detailid)));
                item.setHj(Float.parseFloat(request.getParameter("hj_" + detailid)));//婚假
                item.setKg(Integer.parseInt(request.getParameter("kg_" + detailid)));
                item.setNxj(Float.parseFloat(request.getParameter("nxj_" + detailid)));//年休假
                item.setQt(Float.parseFloat(request.getParameter("qt_" + detailid)));//其他
                item.setSfcq(Integer.parseInt(request.getParameter("sfcq_" + detailid)));
                item.setSfjb(Integer.parseInt(request.getParameter("sfjb_" + detailid)));
                item.setShij(Float.parseFloat(request.getParameter("shij_" + detailid)));//事假
                item.setSj(Float.parseFloat(request.getParameter("sj_" + detailid)));//丧假
                item.setSyj(Float.parseFloat(request.getParameter("syj_" + detailid)));//生育假
                item.setTqj(Float.parseFloat(request.getParameter("tqj_" + detailid)));//探亲假
                item.setYgzs(Float.parseFloat(request.getParameter("ygzs_" + detailid)));//因公致伤
                item.setZt(Integer.parseInt(request.getParameter("zt_" + detailid)));
                item.setRemark(request.getParameter("remark_" + detailid));
                item.setAttdetailid(detailid);
                lst.add(item);
            }

            Long attsummaryid = Long.parseLong(strattsummaryid);

            int iResult = 0;
            iResult = iAttBmHzService.UpdateBmHz(lst, attsummaryid);

            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }

    @RequestMapping(value = "/add_attbmhznodetail")
    public String AddAttBmHzNoDetail(HttpServletRequest request, HttpServletResponse response) {
        try {
            String strattsummaryid = request.getParameter("attsummaryid");
            Long attsummaryid = Long.parseLong(strattsummaryid);

            AttSummaryEntity sumentityget = iAttTbService.GetAttTbAttsummaryById(attsummaryid);
            int qqtsset = iAttBmHzService.GetQqDaysByYearAndMonth(sumentityget.getYear(), sumentityget.getMouth());
            if (qqtsset <= 0) {
                return renderStringScript(response, "<script>window.parent.CloseDialog(0,'未配置本月出勤天数')</script>");
            }

            AttSummaryEntity sumentity = new AttSummaryEntity();
            sumentity.setAttsummaryid(attsummaryid);
            //sumentity.setCqts(Float.parseFloat(request.getParameter("cqts")));
            sumentity.setCqts(qqtsset);
            sumentity.setXjts(Float.parseFloat(request.getParameter("xjts")));
            if (sumentity.getXjts() > 15) {
                return renderStringScript(response, "<script>window.parent.CloseDialog1()</script>");

            }
            sumentity.setTqjts(Float.parseFloat(request.getParameter("tqjts")));
            sumentity.setHjts(Float.parseFloat(request.getParameter("hjts")));
            sumentity.setSangjts(Float.parseFloat(request.getParameter("sangjts")));
            sumentity.setBjts(Float.parseFloat(request.getParameter("bjts")));
            sumentity.setSyjts(Float.parseFloat(request.getParameter("syjts")));
            sumentity.setSjts(Float.parseFloat(request.getParameter("sjts")));
            sumentity.setGsts(Float.parseFloat(request.getParameter("gsts")));
            sumentity.setQtts(Float.parseFloat(request.getParameter("qtts")));
            sumentity.setSfjb(Integer.parseInt(request.getParameter("sfjb")));

            sumentity.setCdcc(Integer.parseInt(request.getParameter("cdcc")));
            sumentity.setZtcc(Integer.parseInt(request.getParameter("ztcc")));
            sumentity.setKgcs(Integer.parseInt(request.getParameter("kgcs")));


            sumentity.setBsjts(sumentity.getBjts() + sumentity.getSjts());
            sumentity.setGsycjts(sumentity.getGsts() + sumentity.getSyjts());

            sumentity.setRemark(request.getParameter("remark"));
            if (qqtsset < sumentity.getCqts()) {
                return renderStringScript(response, "<script>window.parent.CloseDialog(0,'出勤天数超出当月应出勤天数上限')</script>");
            }

            if (qqtsset == sumentity.getCqts()) {
                sumentity.setSfqq(1);
            } else {
                sumentity.setSfqq(0);
            }

            float wcqtsxj = sumentity.getXjts() + sumentity.getHjts() + sumentity.getTqjts() + sumentity.getSyjts() + sumentity.getSjts() + sumentity.getGsts() + sumentity.getBjts() + sumentity.getSangjts() + sumentity.getQtts();
            sumentity.setWcqtsxj(wcqtsxj);

            int iResult = 0;
            iResult = iAttBmHzService.UpdateBmHzNoDetail(sumentity);

            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }


    @ResponseBody
    @RequestMapping(value = "/export_excel")
    public ExceResult ExportExcel(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {


            String year = request.getParameter("year");
            String mouth = request.getParameter("mouth");

            String orgid = request.getParameter("orgid");
            String orgsummaryid = request.getParameter("orgsummaryid");

            String where = "";
            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (mouth != null && mouth.length() > 0) {
                where += " AND mouth=" + mouth;
            }

            if (orgid != null && orgid.length() > 0) {
                where += " AND szdw IN (" + orgid + ")";
            } else {
                where += " AND szdw IN (" + this.GetOrgListByRole() + ")";
            }

            if (orgsummaryid != null && orgsummaryid.length() > 0) {
                where += " AND orgsummaryid=" + orgsummaryid;
            }

            List<AttSummaryEntity> lst = iAttTbService.GetAttTbListByWhere(where);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

            String finalXlsxPath = ConfigOption.getInstance().getTemplateurl() + "/kqtemp.xlsx";
            String filename = "kaoqin_" + sdf.format(new Date()) + ".xlsx";
            String titile = "房山公安分局" + lst.get(0).getOrgname() + " " + lst.get(0).getYear() + "年" + lst.get(0).getMouth() + "月考勤";

            Boolean olResult = ExcelHandler.writeExcelKq(lst, finalXlsxPath, filename, titile, response);
            if (olResult) {
                result.setCode(200);
                result.setResult(1);
                String urlen = ConfigOption.getInstance().getWeburl() + filename;
                result.setMsg(urlen);
            } else {
                result.setCode(300);
                result.setResult(0);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/export_ck_excel")
    public ExceResult ExportckExcel(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String start = request.getParameter("start");
            String end = request.getParameter("endt");

            String orgid = request.getParameter("orgid");

            String realname = request.getParameter("realname");
            String status = request.getParameter("atttype");

            String where = "";
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);

            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM");
            if (start != null && start.length() > 0) {
                Date date = sDateFormat.parse(start);
                Calendar cale = Calendar.getInstance();
                cale.setTime(date);
                int yeare = cale.get(Calendar.YEAR);
                int monthe = cale.get(Calendar.MONTH) + 1;
                where += " AND year >= " + yeare + " AND mouth >= " + monthe;
            } else {

                Date date = new Date();
                where += " AND year >= " + year + " AND mouth >= " + month;
            }

            if (end != null && end.length() > 0) {
                Date date = sDateFormat.parse(end);
                Calendar cale = Calendar.getInstance();
                cale.setTime(date);
                int yeare = cale.get(Calendar.YEAR);
                int monthe = cale.get(Calendar.MONTH) + 1;
                where += " AND year <= " + yeare + " AND mouth <= " + monthe;
            } else {
                Date date = new Date();
                where += " AND year <= " + year + " AND mouth <= " + month;
            }


            if (orgid != null && orgid.length() > 0 && !orgid.equals("0")) {
                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(orgid));
                where += " AND szdw IN (SELECT orgid FROM t_sys_org WHERE lft>= " + orgentity.getLft() + " AND lft<=" + orgentity.getRgt() + ")";
            } else {
                where += " AND szdw IN (" + this.GetOrgListByRole() + ")";
            }

            if (realname != null && realname.length() > 0) {
                where += " AND userid IN (SELECT userid FROM t_sys_user WHERE cardno LIKE '%" + realname + "%'  or realname LIKE '%" + realname + "%')";
            }
            if (status != null && status.length() > 0 && !status.contains("00")) {
                if (status.contains(",")) {
                    String[] str = status.split(",");
                    for (int i = 0; i < str.length; i++) {
                        if (i == 0) {
                            where += " AND (" + getStatue(Integer.valueOf(str[i]));
                        } else {
                            where += " OR " + getStatue(Integer.valueOf(str[i]));
                        }

                    }
                    where += ") ";
                } else {
                    where += " AND " + getStatue(Integer.valueOf(status));
                }
            } else {

                where += " AND wcqtsxj > 0 ";
            }

            List<AttSummaryEntity> lst = iAttTbService.GetAttTbListByWhere(where);
            String showmonth = "";
            HashSet<String> monthkey = new HashSet();
            for (AttSummaryEntity attSummaryEntity : lst) {
                String key = String.valueOf(attSummaryEntity.getMouth());
                if (!monthkey.contains(key)) {
                    if (showmonth.equals(""))
                        showmonth = key;
                    else
                        showmonth += "," + key;
                    monthkey.add(String.valueOf(attSummaryEntity.getMouth()));
                }
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String finalXlsxPath = ConfigOption.getInstance().getTemplateurl() + "/kqtemp.xlsx";
            String filename = "kaoqin_" + sdf.format(new Date()) + ".xlsx";
//            String titile = "房山公安分局" + lst.get(0).getOrgname() + " " + lst.get(0).getYear() + "年" + lst.get(0).getMouth() + "月考勤";
            String titile = "房山公安分局" + lst.get(0).getOrgname() + " " + lst.get(0).getYear() + "年" + showmonth + "月考勤";

            Boolean olResult = ExcelHandler.writeExcelKq(lst, finalXlsxPath, filename, titile, response);
            if (olResult) {
                result.setCode(200);
                result.setResult(1);
                String urlen = ConfigOption.getInstance().getWeburl() + filename;
                result.setMsg(urlen);
            } else {
                result.setCode(300);
                result.setResult(0);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/create_atttb")
    public ExceResult CreateAttTb(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String strorgid = request.getParameter("orgid");
            String stryear = request.getParameter("year");
            String strmonth = request.getParameter("month");

            Long orgid = Long.parseLong(strorgid);
            Long byuserid = this.GetLoginUserId();
            int year = Integer.parseInt(stryear);
            int month = Integer.parseInt(strmonth);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(sdf.parse(year + "-" + month + "-1"));
            int countday = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);


            AttTbBatchEntity entity = new AttTbBatchEntity();
            entity.setByuserid(byuserid);
            entity.setDay(0);
            entity.setDays(countday);
            entity.setMonth(month);
            entity.setOrgid(orgid);
            entity.setYear(year);
            switch (month) {
                case 1:
                case 2:
                case 3:
                    entity.setQuarter(1);
                    break;
                case 4:
                case 5:
                case 6:
                    entity.setQuarter(2);
                    break;
                case 7:
                case 8:
                case 9:
                    entity.setQuarter(3);
                    break;
                case 10:
                case 11:
                case 12:
                    entity.setQuarter(4);
                    break;
            }

            int iResult = 0;
            int iExit = iOrgSummaryService.GetExitOrgSummary(orgid, year, month, "att");
            //System.out.println(iExit+" "+orgid+" "+year+" "+month);
            if (iExit > 0) {
                result.setCode(400);
                result.setResult(iExit);
                result.setMsg("该机构该年度该月已生成考勤(" + year + "年" + month + "月)");
                return result;

            }

            iResult = iAttTbService.CreateInsertAttTb(entity);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/create_atttb_nodetail")
    public ExceResult CreateAttTbNoDetail(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String strorgid = request.getParameter("orgid");
            String stryear = request.getParameter("year");
            String strmonth = request.getParameter("month");

            Long orgid = Long.parseLong(strorgid);
            Long byuserid = this.GetLoginUserId();
            UserEntity byuser = this.GetUserById(byuserid);
            int year = Integer.parseInt(stryear);
            int month = Integer.parseInt(strmonth);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            int yearNow = calendar.get(Calendar.YEAR);
            int monthNow = calendar.get(Calendar.MONTH)+1;
            int dateNow = calendar.get(Calendar.DAY_OF_MONTH);

            calendar.setTime(sdf.parse(year + "-" + month + "-1"));
            int countday = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

            //当前月就提示25日,大于当月直接报错。
            if ((month == monthNow && dateNow < 25) || monthNow < month) {
                result.setCode(400);
                result.setResult(0);
                result.setMsg("请于当月25日后提报考勤！");
                return result;
            }


            //byuserszdw,byuserrsgxszdw,byuseruserstatus,byuserszdwname,byuserrsgxszdwname
            AttTbBatchEntity entity = new AttTbBatchEntity();
            entity.setByuserid(byuserid);
            entity.setByuserrsgxszdw(byuser.getRsgxszdw());
            entity.setByuserrsgxszdwname(byuser.getRsgxorgname());
            entity.setByuserszdw(byuser.getSzdw());
            entity.setByuserszdwname(byuser.getOrgname());
            entity.setByuseruserstatus(byuser.getUserstatus());
            entity.setDay(0);
            entity.setDays(countday);
            entity.setMonth(month);
            entity.setOrgid(orgid);
            entity.setYear(year);
            //生成考核人员信息，冗余字段在这里补充。

            switch (month) {
                case 1:
                case 2:
                case 3:
                    entity.setQuarter(1);
                    break;
                case 4:
                case 5:
                case 6:
                    entity.setQuarter(2);
                    break;
                case 7:
                case 8:
                case 9:
                    entity.setQuarter(3);
                    break;
                case 10:
                case 11:
                case 12:
                    entity.setQuarter(4);
                    break;
            }

            int iResult = 0;
            int iExit = iOrgSummaryService.GetExitOrgSummary(orgid, year, month, "att");
            //System.out.println(iExit+" "+orgid+" "+year+" "+month);
            if (iExit > 0) {
                result.setCode(400);
                result.setResult(iExit);
                result.setMsg("该机构该年度该月已生成考勤(" + year + "年" + month + "月)");
                return result;

            }


            int qqtsset = iAttBmHzService.GetQqDaysByYearAndMonth(year, month);
            if (qqtsset <= 0) {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("未配置本月出勤天数");
                return result;
            }
            entity.setDays(qqtsset);

            iResult = iAttTbService.CreateInsertAttTbNoDetail(entity);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_org_summary_list")
    public LayTable<Map> GetOrgSummaryList(HttpServletRequest request) {

        List<Map> lst = null;
        LayTable<Map> layTable = new LayTable<Map>();
        try {
            int year = Integer.parseInt(request.getParameter("year"));
            int month = Integer.parseInt(request.getParameter("month"));

            Calendar cal = Calendar.getInstance();
            int currentyear = cal.get(Calendar.YEAR);
            int currentmonth = cal.get(Calendar.MONTH) + 1;
            if (currentyear != year) {
                currentmonth = 12;
            }


            Integer iexit = iOrgSummaryService.GetOrgYearCount("att", year, 0);
            if (iexit == 0) {
                List<Integer> list = new ArrayList<Integer>();
                for (int i = 0; i < 12; i++) {
                    list.add(i + 1);
                }
                iOrgSummaryService.InsertOrgYearBacth(list, year);
            }


            String where = "";
            where += " AND orgid IN (" + this.GetOrgListByRole() + ")";
            lst = iOrgSummaryService.GetOrgSummaryList(where, year, month, "", currentmonth);

            layTable.setCode(0);
            layTable.setCount(lst.size());
            layTable.setData(lst);

        } catch (Exception e) {
            e.printStackTrace();
            layTable.setCode(500);
        }
        return layTable;
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_org_summary_Sh_list")
    public LayTable<Map> GetOrgSummaryShList(HttpServletRequest request) {

        List<Map> lst = null;
        LayTable<Map> layTable = new LayTable<Map>();
        try {
            int year = Integer.parseInt(request.getParameter("year"));
            int month = Integer.parseInt(request.getParameter("month"));

            Calendar cal = Calendar.getInstance();
            int currentyear = cal.get(Calendar.YEAR);
            int currentmonth = cal.get(Calendar.MONTH);
            if (currentyear != year) {
                currentmonth = 12;
            }
            String where = "";
            where += " AND orgid IN (" + this.GetOrgListByRole() + ")";

            //先不传，全部取出。因为重新生成PDF 的需要看数据
            lst = iOrgSummaryService.GetOrgSummaryList(where, year, month, "", currentmonth);

            //int iCount=iAttTbService.GetAttTbListCountByWhere(where);
            //System.out.println(JSONObject.toJSONString(lst));
            layTable.setCode(0);
            layTable.setCount(lst.size());
            layTable.setData(lst);

        } catch (Exception e) {
            e.printStackTrace();
            layTable.setCode(500);
        }
        return layTable;
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_org_summary_list_grid")
    public GridCommon<Map> GetOrgSummaryListGrid(HttpServletRequest request) {

        List<Map> lst = null;
        GridCommon<Map> countlist = new GridCommon<Map>();
        try {
            int year = Integer.parseInt(request.getParameter("year"));
            int month = Integer.parseInt(request.getParameter("month"));
            String where = "";

            Calendar cal = Calendar.getInstance();
            int currentyear = cal.get(Calendar.YEAR);
            int currentmonth = cal.get(Calendar.MONTH) + 1;
            if (currentyear != year) {
                currentmonth = 12;
            }

            Integer iexit = iOrgSummaryService.GetOrgYearCount("att", year, 0);
            if (iexit == 0) {
                List<Integer> list = new ArrayList<Integer>();
                for (int i = 0; i < 12; i++) {
                    list.add(i + 1);
                }
                iOrgSummaryService.InsertOrgYearBacth(list, year);
            }

            //where+=this.GetLoginUserForOtherListWhereByUserId();
            where += " AND orgid IN (" + this.GetOrgListByRole() + ")";
            lst = iOrgSummaryService.GetOrgSummaryList(where, year, month, "", currentmonth);
//            for (Map map : lst) {
//                for (Object o : map.keySet()) {
//                    //有状态
//                    if(o.toString().equals("status")){
//                        String realCount = map.get("realusercount").toString();
//                        map.put("")
//                    }
//                }
//            }

            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(lst);
            countlist.setStatus(0);
            countlist.setMsg("");
            countlist.setCountRecord(lst.size());

        } catch (Exception e) {
            e.printStackTrace();
            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(null);
            countlist.setStatus(1);
            countlist.setMsg("操作成功");
        }
        return countlist;
    }


    @ResponseBody
    @RequestMapping(value = "/update_attstatus")
    public ExceResult UpdateAttStatus(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String strorgsummaryid = request.getParameter("orgsummaryid");
            String strstatus = request.getParameter("status");

            Long orgsummaryid = Long.parseLong(strorgsummaryid);
            int status = Integer.parseInt(strstatus);

            int iResult = 0;

            if (status == 4) {//审批状态，同时更新审批人
                Long userid = GetLoginUser().getUserid();//审批人用户ID
                iResult = iAttBmHzService.UpdateAttStatusAppUser(orgsummaryid, userid, status);
            } else {
                iResult = iAttBmHzService.UpdateAttStatus(orgsummaryid, status);
            }
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/update_approverUser")
    public ExceResult UpdateApprover(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String strorgsummaryid = request.getParameter("orgsummaryid");

            Long userid = GetLoginUser().getUserid();//审批人用户ID
            Long orgsummaryid = Long.parseLong(strorgsummaryid);

            int iResult = 0;
            iResult = iAttTbService.UpdateApproverUser(orgsummaryid, userid);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/createPDF")
    public int uploadBillClient(HttpServletRequest request
    ) throws IOException {

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码

            byte[] b = decoder.decodeBuffer(request.getParameter("file"));
            String year = request.getParameter("year");
            String month = request.getParameter("month");
            String orgid = request.getParameter("orgid");
            for (int i = 0; i < b.length; ++i) {
                // 调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            String fileName = year + "/" + month + "/" + orgid + "/file.pdf";
            String filePath = "";


            filePath = ConfigOption.getInstance().getFileurl() + "/pdf/";
            fileName = filePath + fileName;


            File file = new File(fileName);
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            OutputStream out = new FileOutputStream(fileName);
            out.write(b);
            out.flush();
            out.close();


        } catch (Exception e) {


            txtExport.creatTxtFile("考勤导出");
            StackTraceElement[] stackTrace = e.getStackTrace();
            String errorMsg = e.toString() + "<br/>";
            for (int i = 0; i < stackTrace.length; i++) {
                errorMsg += stackTrace[i];
                errorMsg += "<br/>";
            }
            txtExport.writeTxtFile(errorMsg);


            return 0;
        }
        return 1;
    }

    @ResponseBody
    @RequestMapping(value = "/showPDF")
    public String lookPdf(HttpServletRequest request
    ) {
        List<Map> lst = null;

        try {
            String type = request.getParameter("type");// 1 查看上月  2查看当月

            List<Configure> configureList = new ArrayList<>();
            configureList = configureService.getAll(" and  code='kaoqin' and type=" + type + "");

            if (configureList.size() > 0) {
                Date d = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  ");
                Configure configure = configureList.get(0);

                Date start = sdf.parse(sdf.format(configure.getStarttime()));
                Date end = sdf.parse(sdf.format(configure.getEndtime()));
                Date now = sdf.parse(sdf.format(d));
                if (start.getTime() <= now.getTime() && end.getTime() >= now.getTime()) {
                    int year = Integer.parseInt(request.getParameter("year"));
                    int month = Integer.parseInt(request.getParameter("month"));


                    Calendar cal = Calendar.getInstance();
                    int currentyear = cal.get(Calendar.YEAR);
                    int currentmonth = cal.get(Calendar.MONTH) + 1;
                    if (currentyear != year) {
                        currentmonth = 12;
                    }
                    String where = "";
                    where += " AND orgid IN (" + this.GetLoginUser().getSzdw() + ")";


                    lst = iOrgSummaryService.GetOrgSummaryListPDF(where, year, month, "4", currentmonth);

                    if (lst.size() > 0) {

                        String webUrl = "http://127.0.0.1:8081/";
                        webUrl = ConfigOption.getInstance().getWeburl();
                        return webUrl + "pdf/" + year + "/" + month + "/" + this.GetLoginUser().getSzdw() + "/file.pdf";

                    }

                }
            }


        } catch (Exception ex) {
            String exs = ex.getMessage();
        }

        return "";
    }


}